/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.wpi.first.wpilibj.defaultCode;

/**
 *
 * @author beto
 *
 * Maintains a circular buffer and calculates the moving average
 * of the last "n" entries, and where "n" is user specified
 *
 *
 */
public class Averager {

    double[] buf;
    int tail;
    public static int BUF_SIZE = 50;

    
    
    public Averager()
    {
        buf = new double[BUF_SIZE];
        tail = 0;
    }
    
    
    public void AddEntry(double newEntry)
    {
        buf[tail] = newEntry;
        tail++;
        if( tail > BUF_SIZE-1 )
            tail = 0;
    }
    
    
    public double GetAvg( int numEntriesToAvg )
    {
        double avg = 0.0;
        double sum = 0.0;
        int start, end;
        int i;

        if( numEntriesToAvg < 1 )
            numEntriesToAvg = 1;
        if( numEntriesToAvg > BUF_SIZE )
            numEntriesToAvg = BUF_SIZE;
        
        end = tail - 1;
        if( end < 0 )
            end = BUF_SIZE - 1;
        
        start = end - numEntriesToAvg + 1;
        if( start < 0 )
            start = start + BUF_SIZE;

        if( end >= start )
        {
            for(i=start; i<end+1; i++)
                sum = sum + buf[i];
        }
        else
        {
            for( i=start; i<BUF_SIZE; i++ )
                sum = sum + buf[i];
            for( i=0; i<end+1; i++ )
                sum = sum + buf[i];
        }

        avg = sum /(double)numEntriesToAvg;
        
        return avg;

    }











}
